import os

from .framework import *

keywords = [
    'uuid',
    'steps',
    'step',
]

def steps(classz=None):
    '''步骤列表'''
    if classz is None:
        return get('steps')
    set('steps', list(class_keys(classz).values()))
    
def step(t=None):
    '''当前步骤号'''
    if t is None:
        return get('step')
    else:
        set('step',t)
        return 0

def current():
    '''当前步骤'''
    return steps()[step()]

def prev_step(automatic=True):
    '''上一步'''
    if not automatic:
        if st.button('上一步'):
            prev_step()
        return
    step(step()-1)
    st.rerun()

def next_step(automatic=True):
    '''下一步'''
    if not automatic:
        if st.button('下一步'):
            next_step()
        return
    step(step()+1)
    st.rerun()


def work(classz=None):
    '''工作对象'''
    
    if classz is None:
        return get('work')
    
    set('uuid', uuid())
    set('workdir', f'/tmp/.spk-online-workdir/{get("uuid")}')
    os.makedirs(get('workdir'), mode=0o777)
    
    step(0)
    steps(classz)
    
    set('work', classz())

def workdir():
    return get('workdir')
    
def cleanwork():
    if work():
        work().__do_clean__()
        set('work', None)

    if get('workdir') is not None:
        if str(get('workdir')).startswith('/tmp/.spk-online-workdir'):
            os.system(f'rm -rf "{get("workdir")}"')
    for k in keywords:
        unset(k)


def show_step_control():
    if step() == 0:
        st.button('下一步', on_click=next_step)
        return
    if step() < len(get('steps'))-1:
        cols = st.columns(2, gap='small')
        with cols[0]:
            st.button('上一步', on_click=prev_step)
        with cols[1]:
            st.button('下一步', on_click=next_step)
    else:
        st.button('上一步', on_click=prev_step)
